<div class="row">
    <div class="col-md-12">
        <div id="buttonBar" class="box-widget">
        <button id="addBuyDialog" class="btn btn-success">
            Bán hàng
        </button>
        <button id="addSaleDialog" class="btn btn-info">
            Mua hàng
        </button>
        <button id="addPaymentDialog" class="btn btn-account">
            Tài khoản
        </button>
        <form style="float: right;" method="get">
        Từ ngày: 
        <input type="text" name="from" id="dateFrom" value="<?php echo $this->dateFrom; ?>" />
        Đến ngày: 
        <input type="text" name="to" id="dateTo" value="<?php echo $this->dateTo; ?>" />
        <button class="btn btn-info" type="submit">Tìm</button>
        </form>
        </div>
        <div class="box-widget">
            <table id="list-group" class="table data-tbl-boxy responsive">
                <thead>
                    <tr>
                        <th id="date" class="text-center">
                            Ngày
                        </th>
                        <th id="name" class="text-center">
                            Tên khách hàng
                        </th>
                        <th id="sale" class="text-center">
                            Bán hàng
                        </th>
                        <th id="buy" class="text-center">
                            Mua hàng
                        </th>
                        <th id="payment" class="text-center">
                            Tài khoản
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <?php $i = 0; ?>
                    <?php foreach($this->data as $key => $row): ?>
                    <?php
                        $length = count($row['buy']);
                        $length = (count($row['sale']) > $length) ? count($row['sale']) : $length;
                        $length = (count($row['payment']) > $length) ? count($row['sale']) : $length; 
                        
                        $buy = $row['buy'];
                        $sale = $row['sale'];
                        $payment = $row['payment'];
                        $order_buys = $row['order_buys'];
                    ?>
                    <tr>
                       <td>
                            <?php echo  date("d-m-Y", strtotime($key)); ?>
                       </td>
                       <td></td>
                       <td></td>
                       <td></td>
                       <td></td>
                    </tr>
                    <?php $i ++; ?>
                    <?php foreach($buy as $b): ?>
                    <tr>
                        <td class="<?php if($i % 100 != 0) echo 'text-center'; ?>">
                            <?php 
                                if($i % 100 == 0){
                                    echo date("d-m-Y", strtotime($key));
                                }else{
                                    echo "-";
                                } 
                            ?>
                        </td>
                        <td class="name buy">
                            <strong>
                                <?php echo $b['name']; ?>
                            </strong>
                            <button onclick="deleteRow(<?php echo $b['id']; ?>)" class="btn btn-mini btn-danger">Xóa</button>
                        </td>
                        <td class="text-center buy">
                            <?php echo number_format($b['total'], 0, null, "."); ?>
                        </td>
                        <td class="text-center">
                            -
                        </td>
                        <td>
                            -
                        </td>
                    </tr>
                    <?php $i ++; ?>
                    <?php endforeach; ?>
                    
                    <?php foreach($sale as $s): ?>
                    <tr>
                        <td class="<?php if($i % 100 != 0) echo 'text-center'; ?>">
                            <?php 
                                if($i % 100 == 0){
                                    echo date("d-m-Y", strtotime($key));
                                }else{
                                    echo "-";
                                } 
                            ?>
                        </td>
                        <td class="name sale">
                            <strong>
                                <?php echo $s['name']; ?>
                            </strong>
                            <button onclick="deleteRow(<?php echo $s['id']; ?>)" class="btn btn-mini btn-danger">Xóa</button>
                        </td>
                        <td class="text-center">
                            -
                        </td>
                        <td class="text-center sale">
                            <?php echo number_format($s['total'], 0, null, "."); ?>
                        </td>
                        <td class="text-center">
                            -
                        </td>
                    </tr>
                    <?php $i ++; ?>
                    <?php endforeach; ?>
                    
                    <?php /* foreach($order_buys as $o): ?>
                    <tr>
                        <td class="<?php if($i % 100 != 0) echo 'text-center'; ?>">
                            <?php 
                                if($i % 100 == 0){
                                    echo date("d-m-Y", strtotime($key));
                                }else{
                                    echo "-";
                                } 
                            ?>
                        </td>
                        <td class="name sale">
                            <strong>
                                <?php echo $o['name']; ?>
                            </strong>
                        </td>
                        <td class="text-center">
                            -
                        </td>
                        <td class="text-center sale">
                            <?php echo number_format(($o['total'] / 1000), 0, null, "."); ?>
                        </td>
                        <td class="text-center">
                            -
                        </td>
                    </tr>
                    <?php $i ++; ?>
                    <?php endforeach; */ ?>
                    
                    <?php foreach($payment as $p): ?>
                    <tr>
                        <td class="<?php if($i % 100 != 0) echo 'text-center'; ?>">
                            <?php 
                                if($i % 100 == 0){
                                    echo date("d-m-Y", strtotime($key));
                                }else{
                                    echo "-";
                                } 
                            ?>
                        </td>
                        <td class="name payment">
                            <strong>
                                <?php echo $p['name']; ?>
                            </strong>
                            <button onclick="deleteRow(<?php echo $p['id']; ?>)" class="btn btn-mini btn-danger">Xóa</button>
                        </td>
                        <td class="text-center">
                            -
                        </td>
                        <td class="text-center">
                            -
                        </td>
                        <td class="text-center payment">
                            <strong>
                                <?php echo $p['receiver']; ?>
                            </strong>: 
                            <?php echo number_format($p['total'], 0, null, "."); ?>
                        </td>
                    </tr>
                    <?php $i ++; ?>
                    <?php endforeach; ?>
                    
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td class="name" colspan="2">Tổng cộng: </td>
                        <td class="total text-center">
                            <?php echo number_format($this->totalBuy, 0, null, "."); ?>
                        </td>
                        <td class="total text-center">
                            <?php
                                $totalSale = $this->totalSale;// + ($this->totalOrderBuys / 1000);
                            ?>
                            <?php echo number_format($totalSale, 0, null, "."); ?>
                        </td>
                        <td class="total text-center">
                            <?php echo number_format($this->totalPayment, 0, null, "."); ?>
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>
<div id="add-buy" title="Nhập bán hàng">
    <form id="add-buy-form">
        <span id="product-error" style="color: red;">
        
        </span>
        <br />
        Tên khách hàng<br />
        <select name="name">
            <?php foreach($this->customers as $row): ?>
            <option value="<?php echo $row->id; ?>"><?php echo $row->name; ?></option>
            <?php endforeach; ?>
        </select> <br />
        <button type="button" id="addCustomer" class="btn btn-mini btn-success"> Thêm </button> 
        <button type="button" id="deleteCustomer" class="btn btn-mini btn-danger"> Xóa </button>
        <br />
        Số tiền<br />
        <input type="text" name="total" value="" /><br />
        Ngày<br />
        <input type="text" id="date" name="date" value="<?php echo date("d-m-Y"); ?>" /><br />
        <input type="hidden" name="type" value="0" />
    </form>
</div>
<div id="add-customer" title="Thêm khách hàng">
    <form id="add-customer-form">
        Tên khách hàng<br />
        <input type="text" name="name" id="name" /><br />
        Điện thoại<br />
        <input type="text" value="" name="phone_number" id="phone_number" /><br />
        Địa chỉ<br />
        <input type="text" value="" name="address" id="address" />
        <input type="hidden" value="0" name="discount_type" id="discount_type" />
        <input type="hidden" value="0" name="discount_value" id="discount_value" />
        <input type="hidden" name="type" id="type" value="0" /> 
    </form>
</div>
<div id="add-sale" title="Nhập mua hàng">
    <form id="add-sale-form">
        <span id="product-error" style="color: red;">
        
        </span>
        <br />
        Tên khách hàng<br />
        <select name="name">
            <?php foreach($this->suppliers as $row): ?>
            <option value="<?php echo $row->id; ?>"><?php echo $row->name; ?></option>
            <?php endforeach; ?>
        </select><br />
        <button type="button" id="addSupplier" class="btn btn-mini btn-success">Thêm</button>
        <button type="button" id="deleteSupplier" class="btn btn-mini btn-danger"> Xóa </button>
        <br />
        Số tiền<br />
        <input type="text" name="total" value="" /><br />
        Ngày<br />
        <input type="text" id="date2" name="date" value="<?php echo date("d-m-Y"); ?>" /><br />
        <input type="hidden" name="type" value="1" />
    </form>
</div>
<div id="add-payment" title="Nhập tài khoản">
    <form id="add-payment-form">
        <span id="product-error" style="color: red;">
        
        </span>
        <br />
        Tên khách hàng<br />
        <select name="name">
            <?php foreach($this->customers as $row): ?>
            <option value="<?php echo $row->id; ?>"><?php echo $row->name; ?></option>
            <?php endforeach; ?>
        </select><br />
        Số tiền<br />
        <input type="text" name="total" value="" /><br />
        Người nhận<br />
        <input type="text" name="receiver" value="" /><br />
        Ngày<br />
        <input type="text" id="date3" name="date" value="<?php echo date("d-m-Y"); ?>" /><br />
        <input type="hidden" name="type" value="2" />
    </form>
</div>
<script>
function ajaxLoading(){
    var html = '<div class="imgLoading">';
    html += '<img class="imgLoading" src="<?php echo $this->templateURL; ?>/images/ajax-loader/ajax-loader_orange.gif" />';
    html += '</div>';
    
    $("body").append(html);
}

function deleteRow(id){
    var ok = confirm("Bạn muốn xóa dòng này?");
    
    if(ok){
        $.ajax({
            url: "<?php echo $this->url(array('module' => 'admin', 'controller' => 'log', 'action' => 'delete'), null, true); ?>",
            data: {"id": id},
            beforeSend: ajaxLoading(),
            success: function (result){
                //$("div.imgLoading").remove();
                location.reload(); 
            }
        });
    }
}

$(document).ready(function(){
    $(window).scroll(function(){
        if($(this).scrollTop() > 0){
            $("#buttonBar").addClass("fixed");
            $("#list-group_wrapper").addClass("fixed");
            $(".widget-head").addClass("fixed");
            $("table#list-group").addClass("fixed");
        }else{
            $("#buttonBar").removeClass("fixed");
            $("#list-group_wrapper").removeClass("fixed");
            $(".widget-head").removeClass("fixed");
            $("table#list-group").removeClass("fixed");
        }
    });
    
    $("body").on("click", "ul.pagination li", function(){
        $(window).scrollTop(0);
    });
    
    $("#list-group").on("page.dt", function(){
        $(window).scrollTop(0);
    });
    
    var optionNumeric = {'aSep': '.', 'aDec': ',', 'mDec': 0, 'vMin': 0, 'vMax': 999999999999};
    $("input[name='total']").autoNumeric('init', optionNumeric);
    
    var dialogBuy = $("div#add-buy").dialog({
        autoOpen: false,
        height: 350,
        width: 350,
        modal: true,
        buttons: {
            "Thêm": addBuy,
            Cancel: function(){
                dialogBuy.dialog("close");
            }
        },
        close: function(){
            $("form#add-buy-form").trigger("reset");
        }
    });
    
    var dialogCustomer = $("div#add-customer").dialog({
        autoOpen: false,
        height: 350,
        width: 300,
        modal: true,
        buttons: {
            "Thêm": addCustomerAndSupplier,
            Cancel: function(){
                dialogCustomer.dialog("close");
            }
        },
        close: function(){
            $("form#add-customer-form").trigger("reset");
        }
    });
    
    var dialogSale = $("div#add-sale").dialog({
        autoOpen: false,
        height: 350,
        width: 300,
        modal: true,
        buttons: {
            "Thêm": addSale,
            Cancel: function(){
                dialogSale.dialog("close");
            }
        },
        close: function(){
            $("form#add-sale-form").trigger("reset");
        }
    });
    
    var dialogPayment = $("div#add-payment").dialog({
        autoOpen: false,
        height: 450,
        width: 300,
        modal: true,
        buttons: {
            "Thêm": addPayment,
            Cancel: function(){
                dialogPayment.dialog("close");
            }
        },
        close: function(){
            $("form#add-payment-form").trigger("reset");
        }
    });
    
    $("button#addBuyDialog").click(function(){
        dialogBuy.dialog("open");
    });
    
    $("button#addSaleDialog").click(function(){
        dialogSale.dialog("open");
    });
    
    $("button#addPaymentDialog").click(function(){
        dialogPayment.dialog("open");
    });
    
    $("button#addCustomer").click(function(){
        $("form#add-customer-form input#type").val(0);
        dialogCustomer.dialog("open");
    })
    
    $("button#addSupplier").click(function(){
        $("form#add-customer-form input#type").val(1);
        dialogCustomer.dialog("open");
    });
    
    $("button#deleteCustomer").click(function(){
        var ok = confirm("Bạn muốn xóa khách hàng này?");
        
        if(ok){
            var id = $(this).parent("form#add-buy-form").children("select[name='name']").val();
            var url = "<?php echo $this->url(array('module' => 'admin', 'controller' => 'customer', 'action' => 'delete'), null, true); ?>";
            
            $.ajax({
                url: url,
                data: {'id' : id},
                type: "POST",
                beforeSend: ajaxLoading(),
                success: function(result){
                    $("form#add-buy-form select[name='name'] option[value='" + id + "']").remove();
                    $("div.imgLoading").remove();
                }
            });
        }
    });
    
    $("button#deleteSupplier").click(function(){
        var ok = confirm("Bạn muốn xóa khách hàng này?");
        
        if(ok){
            var id = $(this).parent("form#add-sale-form").children("select[name='name']").val();
            var url = "<?php echo $this->url(array('module' => 'admin', 'controller' => 'supplier', 'action' => 'delete'), null, true); ?>";
            
            $.ajax({
                url: url,
                data: {'id' : id},
                type: "POST",
                beforeSend: ajaxLoading(),
                success: function(result){
                    $("form#add-sale-form select[name='name'] option[value='" + id + "']").remove();
                    $("div.imgLoading").remove();
                }
            });
        }
    });
    
    var optionDatePicker = {
        changeMonth: true,
        changeYear: true,
        dateFormat: "dd-mm-yy",
    };
    
    function add(url){
        $.ajax({
            url: url,
            beforeSend: ajaxLoading(),
            success: function (result){
                location.reload(); 
            }
        });
    }
    
    function addCustomer(){
        var url = "<?php echo $this->url(array('module' => 'admin', 'controller' => 'customer', 'action' => 'create-ajax'), null, true) ?>";
        
        addCustomerAndSupplier(url);
    }
    
    function addCustomerAndSupplier(){
        var type = $("form#add-customer-form input#type").val();
        
        type = parseInt(type);
        
        var url = "";
        
        if(type == 0){
            url = "<?php echo $this->url(array('module' => 'admin', 'controller' => 'customer', 'action' => 'create-ajax'), null, true) ?>";
        }else{
            url = "<?php echo $this->url(array('module' => 'admin', 'controller' => 'supplier', 'action' => 'create-ajax'), null, true) ?>";
        }
        
        var name = $("form#add-customer-form input#name").val();
        var phone_number = $("form#add-customer-form input#phone_number").val();
        var address = $("form#add-customer-form input#address").val();
        
        $.ajax({
            url: url,
            data: {'name': name, 'phone_number': phone_number, 'address': address, 'discount_type': 0, 'discount_value': 0},
            beforeSend: ajaxLoading(),
            success: function (result){
                var obj = $.parseJSON(result);
                
                $("div.imgLoading").remove();
                
                if(obj.error == false){
                    var customer = obj.data;
                    var html = '<option value="' + customer.id + '">' + customer.name + '</option>';
                    
                    if(type == 0){
                        $("form#add-buy-form select[name='name']").append(html);
                        $("form#add-buy-form select[name='name'] option[value='" + customer.id + "']").attr("selected", "selected");
                        $("form#add-buy-form select[name='name'] option[value='" + customer.id + "']").prop("selected", true);
                    }else{
                        $("form#add-sale-form select[name='name']").append(html);
                        $("form#add-sale-form select[name='name'] option[value='" + customer.id + "']").attr("selected", "selected");
                        $("form#add-sale-form select[name='name'] option[value='" + customer.id + "']").prop("selected", true);
                    }
                    
                    dialogCustomer.dialog("close");
                }else{
                    var html = '<span id="customer-error" style="color: red;">';
                    html += obj.message.name;
                    html += '</span>';
                    html += '<br />';
                    
                    $("form#add-customer-form").before(html);
                }
            }
        });
    }
    
    function addBuy(){
        var total = $("form#add-buy-form input[name='total']").autoNumeric('get');
        $("form#add-buy-form input[name='total']").val(total);
        
        if(isNaN(total) || total.length == 0){
            alert("Giá tiền phải là số và không được để trống!");
            return;
        }else{
            var data = $("form#add-buy-form").serialize();
            var url = "<?php echo $this->url(array('module' => 'admin', 'controller' => 'log', 'action' => 'add'), null, true); ?>?" + data;
            
            add(url);
            dialogBuy.dialog("close");
        }
    }
    
    function addSale(){
        var total = $("form#add-sale-form input[name='total']").autoNumeric('get');
        $("form#add-sale-form input[name='total']").val(total);
        
        if(isNaN(total) || total.length == 0){
            alert("Giá tiền phải là số và không được để trống!");
            return;
        }else{
            var data = $("form#add-sale-form").serialize();
            var url = "<?php echo $this->url(array('module' => 'admin', 'controller' => 'log', 'action' => 'add'), null, true); ?>?" + data;
            
            add(url);
            dialogSale.dialog("close");
        }
    }
    
    function addPayment(){
        var total = $("form#add-payment-form input[name='total']").autoNumeric('get');
        $("form#add-payment-form input[name='total']").val(total);
        
        if(isNaN(total) || total.length == 0){
            alert("Giá tiền phải là số và không được để trống!");
            return;
        }else{
            var data = $("form#add-payment-form").serialize();
            var url = "<?php echo $this->url(array('module' => 'admin', 'controller' => 'log', 'action' => 'add'), null, true); ?>?" + data;
            
            add(url);
            dialogSale.dialog("close");
        }
    }
        
    $.datepicker.regional["vi-VN"] =
    {
        closeText: "Đóng",
        prevText: "Trước",
        nextText: "Sau",
        currentText: "Hôm nay",
        monthNames: ["Tháng một", "Tháng hai", "Tháng ba", "Tháng tư", "Tháng năm", "Tháng sáu", "Tháng bảy", "Tháng tám", "Tháng chín", "Tháng mười", "Tháng mười một", "Tháng mười hai"],
        monthNamesShort: ["Một", "Hai", "Ba", "Bốn", "Năm", "Sáu", "Bảy", "Tám", "Chín", "Mười", "Mười một", "Mười hai"],
        dayNames: ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"],
        dayNamesShort: ["CN", "Hai", "Ba", "Tư", "Năm", "Sáu", "Bảy"],
        dayNamesMin: ["CN", "T2", "T3", "T4", "T5", "T6", "T7"],
        weekHeader: "Tuần",
        dateFormat: "dd/mm/yy",
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ""
    };
     
    $.datepicker.setDefaults($.datepicker.regional["vi-VN"]);
    
    $( "input#date" ).datepicker(optionDatePicker);
    $( "input#date2" ).datepicker(optionDatePicker);
    $( "input#date3" ).datepicker(optionDatePicker);
    
    $( "#dateFrom" ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 3,
        onClose: function( selectedDate ) {
            $( "#dateTo" ).datepicker( "option", "minDate", selectedDate );
        }
    });
    
    $( "#dateTo" ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 3,
        onClose: function( selectedDate ) {
            $( "#dateFrom" ).datepicker( "option", "maxDate", selectedDate );
        }
    });
});

$(function() {
    var table = $('.data-tbl-boxy').dataTable({
        "sPaginationType": "bootstrap",
        "bSort": false,
        "fnDrawCallback": function(){
            $(window).scrollTop(0);
        },
        "iDisplayLength": 100,
        "oLanguage": {
            "sLengthMenu": "<span class='lengthLabel pull-left'><?php echo $this->translate('entries_per_page'); ?>:</span><span class='lenghtMenu pull-left'> _MENU_</span>",
            "sInfo": "<?php echo $this->translate('show start end records of total'); ?>",
            "sSearch": "<?php echo $this->translate('filter'); ?>:",
            "oPaginate": {
                "sFirst": "<?php echo $this->translate('first page'); ?>",
                "sLast": "<?php echo $this->translate('last page'); ?>",
                "sNext": "<?php echo $this->translate('next page'); ?>",
                "sPrevious": "<?php echo $this->translate('previous page'); ?>"
            }
        },
        "sDom": '<"widget-head clearfix"fl>,<"widget-container"<"widget-block"<"widget-content"t>,,<"table-bottom clearfix"<"tbl-pagination pull-left"p><"tbl-data-info pull-right"i>>',
    });
});
</script>
<style>
table#list-group{
    position: relative;
}

#list-group_wrapper.fixed{
    margin-top: 100px;
}

.page-header{
    display: none;
}

#buttonBar.fixed{
    margin-top: 0px;
    box-shadow: none;
    position: fixed;
    top: 40px;
    left: 240px;
    right: 20px;
    margin-bottom: 0 !important;
    padding-bottom: 20px !important;
    padding-top: 1px;
    z-index: 99999999999999;
}

table#list-group.fixed thead{
    position: fixed;
    top: 135px;
    left: 240px;
    right: 20px;
    z-index: 99999999999999;
    background-color: #f3f3f3;
}

table#list-group.fixed thead th#date{
    width: 185px !important;
}

table#list-group.fixed thead th#name{
    width: 405px !important;
}

table#list-group.fixed thead th#buy{
    width: 140px !important;
}

table#list-group.fixed thead th#sale{
    width: 140px !important;
}

table#list-group.fixed thead th#payment{
    width: 315px !important;
}

table#list-group.fixed{
    margin-top: 138px;
}

#list-group_wrapper div.fixed{
    position: fixed;
    top: 95px;
    left: 240px;
    right: 20px;
    z-index: 99999999999999;
    background-color: #5b5847;
}

.btn-account{
    background-color: #000000;
    border-color: #000000;
    color: #ffffff;
}

td.name{
     text-transform: capitalize;
}

td.total{
    font-weight: bold;
}

.sale{
    color: #0080FF;
}

.buy{
    color: #00B700;
}

div.imgLoading{
    width: 100%;
    height: 100%;
    top:  0;
    left:  0;
    bottom:  0;
    right:  0;
    background-color: #000000;
    opacity: 0.7;
    position: fixed;
    z-index: 99999999999999;
}

img.imgLoading{
    position: fixed;
    top: 50%;
    left: 50%;
    width: 40px;
    height: 40px;
    z-index: 999999999999999;
}
</style>